package org.zebias.study.netty.handle;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;
import org.zebias.study.netty.boot.ChannelStore;
import org.zebias.study.netty.codec.potobuf.SubscribeReqProto;

/**
 * @ClassName SubReqClientHandle
 * @Description 客户端处理器
 * @Author zebias
 * @Date 2020/8/18 11:54
 * @Version 1.0
 **/
public class SubReqClientHandle extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        for (int i = 0; i < 3; i++) {
//            ctx.write(subReq(i));
//        }
//        ctx.flush();
        // 连接上设备之后根据请求ID判断数据类型
        ctx.writeAndFlush(subReq(1));
        ChannelStore.getInstance().add("zebias",ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
        System.out.println("Receive server response : [" + msg + "]");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    private SubscribeReqProto.SubscribeReq subReq(int i) {
        SubscribeReqProto.SubscribeReq.Builder builder = SubscribeReqProto.SubscribeReq.newBuilder();
        builder.setSubReqID(i)
                .setUserName("zebias")
                .setProductName("book")
                .addAddress("Shanghai")
                .addAddress("Nanjing")
                .addAddress("Anhui");
        return builder.build();
    }

    public void sendMessage() {

    }
}
